﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SWS;

public class fish_nav : MonoBehaviour {
    
    // private List<Vector3[]> roads = new List<Vector3[]>();
    private road_data[] roads = null;
    private Vector3[] now_road = null;

    private int next_step;
    private Vector3 forward;
    private Vector3 dst;
    private bool is_walking = false;
    private float total_time = 0;
    private float now_time = 0;
    public float speed = 5.0f;

    public float delay = 3.0f;

	// Use this for initialization
	void Start () {
        this.roads = VerticalPoint5.road_Data;

        if (this.delay <= 0) {
            int index = Random.Range(0, this.roads.Length);
            this.walk_on_road(index);
        }
        else {
            this.Invoke("delay_walk", this.delay);
        }
	}

    void delay_walk() {
        int index = Random.Range(0, this.roads.Length);
        this.walk_on_road(index);
    }

    public void walk_on_road(int index) {
        if (index < 0 || index >= this.roads.Length) {
            return;
        }

        this.now_road = this.roads[index].data;
        if (this.now_road.Length < 2) {
            return;
        }

        this.transform.position = this.now_road[0];
        this.next_step = 1;
        this.walk_to_next();
    }

    void walk_to_next() {
        if (this.next_step >= this.now_road.Length) {
            this.is_walking = false;
            int index = Random.Range(0, this.roads.Length);
            this.walk_on_road(index);
            return;
        }

        Vector3 src = this.transform.position;
        Vector3 dst = this.now_road[this.next_step];
        Vector3 dir = dst - src;
        float len = dir.magnitude;
        if (len <= 0) {
            this.next_step++;
            this.walk_to_next();
            return;
        }

        this.total_time = len / this.speed;
        this.now_time = 0;

        Quaternion rot = this.transform.rotation; 
        this.transform.LookAt(dst);
        this.forward = this.transform.forward;
        this.dst = dst;

        this.transform.rotation = rot;


        this.is_walking = true;
    }
	
	// Update is called once per frame
	void Update () {
		if (!this.is_walking) {
            return;
        }
        float dt = Time.deltaTime;
        this.now_time += dt;
        if (this.now_time > this.total_time) { 
            dt -= (this.now_time - this.total_time);
        }

        this.transform.Translate(this.forward * this.speed * dt, Space.World);

        Quaternion rot = Quaternion.LookRotation(this.forward);
        this.transform.rotation = Quaternion.Slerp(this.transform.rotation, rot, 2 * Time.deltaTime);
        if (this.now_time >= this.total_time) {
            this.next_step++;
            this.walk_to_next();
        }
	}
}
